import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:xiaofanshu_flutter/controller/one_route_map_controller.dart';

class OneRouteMapPage extends StatefulWidget {
  const OneRouteMapPage({super.key});

  @override
  State<OneRouteMapPage> createState() => _OneRouteMapPageState();
}

class _OneRouteMapPageState extends State<OneRouteMapPage> {
  final OneRouteMapController controller = Get.find();
  bool hideButtons = false;
  int? routeId;

  @override
  void initState() {
    super.initState();
    
    // 获取传递的参数
    final arguments = Get.arguments as Map<String, dynamic>?;
    if (arguments != null) {
      hideButtons = arguments['hideButtons'] ?? false;
      // 安全地转换routeId，支持String和int类型
      var routeIdValue = arguments['routeId'];
      if (routeIdValue != null) {
        if (routeIdValue is int) {
          routeId = routeIdValue;
        } else if (routeIdValue is String) {
          routeId = int.tryParse(routeIdValue);
        }
      }
    }
    
    // 如果是查看路线详情，只加载路线数据，不加载其他数据
    if (routeId != null) {
      controller.loadRouteDetail(routeId!);
    } else {
      ever(controller.filteredPins, (_) => controller.updateMarkers());
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  // 位置初始化现在由控制器处理，这里删除旧实现

  // 这些方法现在由控制器处理，这里删除旧实现

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Obx(() => Stack(
        children: [
          // 高德地图
          AMapWidget(
            privacyStatement: const AMapPrivacyStatement(hasShow: true, hasAgree: true, hasContains: true),
            initialCameraPosition: CameraPosition(
              target: controller.currentLocation.value ?? const LatLng(39.9042, 116.4074),
              zoom: controller.currentZoom.value,
            ),
            markers: Set<Marker>.of(controller.markers),
            polylines: Set<Polyline>.of(controller.polylines),
            onMapCreated: (mapController) {
              controller.onMapCreated(mapController);
            },
            onCameraMove: (cameraPosition) {
              controller.onCameraMove(cameraPosition);
            },
            onTap: (latLng) {
              // 地图点击事件 - 关闭弹窗
              if (controller.showFilterPopup.value) {
                controller.toggleFilterPopup();
              }
              if (controller.showStoryPreview.value) {
                controller.closeStoryPreview();
              }
            },
            myLocationStyleOptions: MyLocationStyleOptions(true),
          ),
          
          // 左上角返回按钮和更多选项 - 路线详情模式下显示
          if (hideButtons && routeId != null)
            Positioned(
              top: 50,
              left: 0,
              right: 0,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 返回按钮
                    GestureDetector(
                      onTap: () => Get.back(),
                      child: Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: Colors.white,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2),
                              blurRadius: 6,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: const Icon(
                          Icons.arrow_back,
                          size: 24,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                    // 更多选项按钮
                    GestureDetector(
                      onTap: () => _showMoreOptions(),
                      child: Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: Colors.white,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2),
                              blurRadius: 6,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: const Icon(
                          Icons.more_horiz,
                          size: 24,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          
          // 右上角功能按钮 - 根据hideButtons参数控制显示
          if (!hideButtons)
            Positioned(
              top: 60,
              right: 20,
              child: Column(
                children: [
                  _buildFilterButton(),
                  const SizedBox(height: 15),
                  _buildLocationButton(),
                  const SizedBox(height: 15),
                  _buildZoomInButton(),
                  const SizedBox(height: 15),
                  _buildZoomOutButton(),
                ],
              ),
            ),
          
          // 筛选弹窗 - 路线详情模式下隐藏
          if (!hideButtons && controller.showFilterPopup.value) _buildFilterPopup(),
          
          // 故事预览弹窗 - 路线详情模式下隐藏
          if (!hideButtons && controller.showStoryPreview.value) _buildStoryPreview(),
        ],
      )),
    );
  }

  Widget _buildFilterButton() {
    return GestureDetector(
      onTap: controller.toggleFilterPopup,
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.filter_list, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildLocationButton() {
    return GestureDetector(
      onTap: controller.moveToCurrentLocation,
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.my_location, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildZoomInButton() {
    return GestureDetector(
      onTap: () {
        if (controller.mapController != null) {
          controller.mapController?.moveCamera(
            CameraUpdate.zoomIn(),
          );
        }
      },
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.add, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildZoomOutButton() {
    return GestureDetector(
      onTap: () {
        if (controller.mapController != null) {
          controller.mapController?.moveCamera(
            CameraUpdate.zoomOut(),
          );
        }
      },
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.remove, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildFilterPopup() {
    return Obx(() => Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.95),
          borderRadius: BorderRadius.circular(20),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              offset: const Offset(0, 5),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '选择类别',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Color(0xFF333333),
              ),
            ),
            const SizedBox(height: 10),
            // 添加快速选择按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                TextButton(
                  onPressed: controller.selectAllCategories,
                  child: const Text('全选', style: TextStyle(color: Color(0xFFFF2442))),
                ),
                TextButton(
                  onPressed: controller.clearAllCategories,
                  child: const Text('清空', style: TextStyle(color: Color(0xFF666666))),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: _buildCategoryTags(),
            ),
            const SizedBox(height: 20),
            Row(
              children: [
                const Text('官方认证'),
                const Spacer(),
                Switch(
                  value: controller.showOfficialOnly.value,
                  onChanged: (value) => controller.toggleOfficialOnly(),
                  activeColor: const Color(0xFFFF2442),
                ),
              ],
            ),
            const SizedBox(height: 20),
            // 用户筛选
            TextField(
              decoration: InputDecoration(
                hintText: '输入用户昵称进行筛选',
                prefixIcon: const Icon(Icons.person_search, color: Color(0xFF999999)),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFFCCD5)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFFCCD5)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFF2442)),
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              ),
              onChanged: (value) => controller.nicknameFilter.value = value,
            ),
            const SizedBox(height: 20),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: controller.confirmFilterAndReload,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFFF2442),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                ),
                child: const Text('确认', style: TextStyle(color: Colors.white)),
              ),
            ),
          ],
        ),
      ),
    ));
  }

  List<Widget> _buildCategoryTags() {
    if (controller.categories.isEmpty) {
      return const [Center(child: Text('加载分类中...'))];
    }

    return controller.categories.map((category) {
      String categoryName = category['categoryName'] ?? '未知分类';
      String categoryKey = categoryName.toLowerCase();
      bool isSelected = controller.selectedCategories[categoryKey] ?? false;
      
      return GestureDetector(
        onTap: () => controller.toggleCategory(categoryKey),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 8),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xFFFF2442) : const Color(0xFFFFF0F5),
            border: Border.all(
              color: isSelected ? const Color(0xFFFF2442) : const Color(0xFFFFCCD5),
            ),
            borderRadius: BorderRadius.circular(15),
          ),
          child: Text(
            categoryName,
            style: TextStyle(
              color: isSelected ? Colors.white : const Color(0xFFFF2442),
              fontSize: 12,
            ),
          ),
        ),
      );
    }).toList();
  }

  Widget _buildStoryPreview() {
    return Obx(() {
      if (controller.filteredPins.isEmpty) return const SizedBox.shrink();
      
      // 确保当前索引在有效范围内
      if (controller.currentStoryIndex.value >= controller.filteredPins.length) {
        controller.currentStoryIndex.value = 0;
      }
      if (controller.currentStoryIndex.value < 0) {
        controller.currentStoryIndex.value = 0;
      }
      
      final currentStory = controller.filteredPins[controller.currentStoryIndex.value];
      
      return Positioned(
        bottom: 20,
        left: 20,
        right: 20,
        child: GestureDetector(
          onTap: () => controller.navigateToStoryDetail(currentStory),
          child: Container(
            padding: const EdgeInsets.all(15),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(15),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  currentStory.title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF333333),
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  currentStory.content,
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFF666666),
                  ),
                ),
                const SizedBox(height: 10),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () => controller.navigateToUserProfile(currentStory.authorId ?? ''),
                      child: CircleAvatar(
                        radius: 15,
                        backgroundColor: const Color(0xFFFFF0F5),
                        backgroundImage: currentStory.authorAvatar != null 
                            ? NetworkImage(currentStory.authorAvatar!) 
                            : null,
                        child: currentStory.authorAvatar == null 
                            ? const Icon(Icons.person, size: 12, color: Colors.grey)
                            : null,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      currentStory.author,
                      style: const TextStyle(
                        fontSize: 12,
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const Spacer(),
                    IconButton(
                      icon: const Icon(Icons.arrow_back_ios, size: 16),
                      onPressed: controller.previousStory,
                    ),
                    IconButton(
                      icon: const Icon(Icons.arrow_forward_ios, size: 16),
                      onPressed: controller.nextStory,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      );
    });
  }

  // 显示更多选项底部弹窗
  void _showMoreOptions() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 顶部拖动条
              Container(
                margin: const EdgeInsets.only(top: 8, bottom: 16),
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              // 删除路线选项
              GestureDetector(
                onTap: () {
                  Get.back();
                  _confirmDeleteRoute();
                },
                behavior: HitTestBehavior.opaque,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                  child: Row(
                    children: [
                      Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Colors.red.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: const Icon(
                          Icons.delete_outline,
                          color: Colors.red,
                          size: 24,
                        ),
                      ),
                      const SizedBox(width: 16),
                      const Expanded(
                        child: Text(
                          '删除路线',
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.red,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      const Icon(
                        Icons.chevron_right,
                        color: Colors.grey,
                        size: 20,
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),
            ],
          ),
        ),
      ),
      backgroundColor: Colors.transparent,
    );
  }

  // 确认删除路线
  void _confirmDeleteRoute() {
    if (routeId == null) return;
    
    Get.dialog(
      AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: const Text(
          '确认删除',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        content: const Text(
          '确定要删除这条路线吗？删除后将无法恢复。',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xff666666),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text(
              '取消',
              style: TextStyle(
                fontSize: 16,
                color: Color(0xff666666),
              ),
            ),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.deleteRoute(routeId!);
            },
            child: const Text(
              '删除',
              style: TextStyle(
                fontSize: 16,
                color: Colors.red,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
    );
  }
}